package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.model.City;
import com.szgr.baoyin.model.ProtectAddress;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.RLog;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class AddProtectAddressActivity extends BaseActivity implements AdapterView.OnItemSelectedListener {

    private EditText et_farenName;
    private EditText et_farenPhone;
    private EditText et_changName;
    private EditText et_changPhone;
    private EditText et_techName;
    private EditText et_techPhone;
    private TextView tv_area;
    private EditText et_address;
    private ArrayList<City> dataSheng;
    private ArrayList<City> dataCity;
    private ArrayList<City> dataArea;
    private Dialog dialog;
    private Spinner sp_sheng;
    private Spinner sp_city;
    private Spinner sp_area;
    private ArrayAdapter<String> adapterSheng;
    private ArrayAdapter<String> adapterCity;
    private ArrayAdapter<String> adapterArea;
    private String areaChoose;
    private String areaId;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constant.REQUEST_SUCCESS:
                    if("1".equals((String)msg.obj)){
                        for (City c1 : dataSheng) {
                            adapterSheng.add(c1.getName());
                        }
                    }else if("2".equals((String)msg.obj)){
                        for (City c1 : dataCity) {
                            adapterCity.add(c1.getName());
                        }
                    }else if("3".equals((String)msg.obj)){
                        for (City c1 : dataArea) {
                            adapterArea.add(c1.getName());
                        }
                    }
                    break;
                case 998:
                    ToastUtils.showToast("添加成功");
                    finish();
                    break;
            }
        }
    };
    private String shengChoose;
    private String cityChoose;
    private String cityId;
    private EditText et_company;
    private Intent intent;
    private ProtectAddress address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_protect_address);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("添加地址");
        actionBarConfirm.setVisibility(View.VISIBLE);
    }

    @Override
    public void initView() {
        et_company = (EditText)findViewById(R.id.company_name);
        et_farenName = (EditText) findViewById(R.id.faren_username);
        et_farenPhone = (EditText) findViewById(R.id.faren_phone);
        et_changName = (EditText) findViewById(R.id.changzhang_username);
        et_changPhone = (EditText) findViewById(R.id.changzhang_phone);
        et_techName = (EditText) findViewById(R.id.jishu_username);
        et_techPhone = (EditText) findViewById(R.id.jishu_phone);
        tv_area = (TextView) findViewById(R.id.add_address_choose);
        tv_area.setOnClickListener(this);
        et_address = (EditText) findViewById(R.id.add_address_address);

        initDialog();

        intent = getIntent();
        if(intent.hasExtra("address")){
            actionBarTitle.setText("编辑地址");
            address = (ProtectAddress) intent.getSerializableExtra("address");
            et_company.setText(address.getGsmc());
            et_farenName.setText(address.getGsfzr());
            et_farenPhone.setText(address.getGsfzr_tel());
            et_techName.setText(address.getJsfzr());
            et_techPhone.setText(address.getJsfzr_tel());
            tv_area.setText(address.getArea_info());
            et_address.setText(address.getAddress());

            areaId = address.getArea_id();
            cityId = address.getCity_id();
        }
    }

    /**
     *获取城市列表
     */
    private void getCity(final String code, final String type) {
        if("1".equals(type)){
            dataSheng.clear();
        }else if("2".equals(type)){
            dataCity.clear();
        }else if("3".equals(type)){
            dataArea.clear();
        }

        final StringRequest jor = new StringRequest(Request.Method.POST, Constant.URL_CITY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String str) {
                        try {
                            System.out.println("--result-->" + str);
                            JSONObject jsonObject = new JSONObject(str);
                            JSONObject datas = jsonObject.getJSONObject("datas");
                            JSONArray area_list = datas.getJSONArray("area_list");
                            if(area_list.length() == 0){
                                areaChoose = "";
                                areaId = "";
                            }
                            for (int i = 0; i < area_list.length(); i++) {
                                JSONObject json = (JSONObject) area_list.get(i);
                                City c = new City();
                                c.setId(json.getString("area_id"));
                                c.setName(json.getString("area_name"));
                                if("1".equals(type)){
                                    dataSheng.add(c);
                                }else if("2".equals(type)){
                                    dataCity.add(c);
                                }else if("3".equals(type)){
                                    dataArea.add(c);
                                }
                            }
                            mHandler.obtainMessage(Constant.REQUEST_SUCCESS,type).sendToTarget();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap map = new HashMap();
                map.put("area_id", code);
                map.put("key", MyApplication.getmInstance().getKey());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(jor);
    }

    private void initDialog() {
        dataSheng = new ArrayList<>();
        dataCity = new ArrayList<>();
        dataArea = new ArrayList<>();
        View view = LayoutInflater.from(this).inflate(R.layout.layout_add_address,null);
        dialog = DialogUtils.showCustomerDialog(this, view);
        sp_sheng = (Spinner) view.findViewById(R.id.address_sheng);
        sp_city = (Spinner) view.findViewById(R.id.address_city);
        sp_area = (Spinner) view.findViewById(R.id.address_area);
        view.findViewById(R.id.add_address_cancel).setOnClickListener(this);
        view.findViewById(R.id.add_address_confirm).setOnClickListener(this);

        adapterSheng = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        sp_sheng.setAdapter(adapterSheng);
        sp_sheng.setOnItemSelectedListener(this);
        adapterCity = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        sp_city.setAdapter(adapterCity);
        sp_city.setOnItemSelectedListener(this);
        adapterArea = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
        sp_area.setAdapter(adapterArea);
        sp_area.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.action_bar_confirm:
                chargeNull();

                if(!intent.hasExtra("address")){
                    doAdd();
                }else{
                    doEdit();
                }
                break;
            case R.id.add_address_choose:
                adapterSheng.clear();
                getCity("0", "1");
                dialog.show();
                break;
            case R.id.add_address_cancel:
                dialog.dismiss();
                break;
            case R.id.add_address_confirm:
                tv_area.setText(shengChoose + cityChoose + areaChoose);
                dialog.dismiss();
                break;
        }
    }

    private void chargeNull() {
        if(TextUtils.isEmpty(et_company.getText().toString().trim())){
            ToastUtils.showToast("请填写公司名称");
            return;
        }

        if(TextUtils.isEmpty(et_farenName.getText().toString().trim())){
            ToastUtils.showToast("请填写法人代表");
            return;
        }

        if(TextUtils.isEmpty(et_farenPhone.getText().toString().trim())){
            ToastUtils.showToast("请填写法人代表手机号码");
            return;
        }

        if(TextUtils.isEmpty(et_techName.getText().toString().trim())){
            ToastUtils.showToast("请填写技术代表");
            return;
        }

        if(TextUtils.isEmpty(et_techPhone.getText().toString().trim())){
            ToastUtils.showToast("请填写技术代表手机号码");
            return;
        }

        if(TextUtils.isEmpty(tv_area.getText().toString().trim())){
            ToastUtils.showToast("请填写公司所在地区");
            return;
        }

        if(TextUtils.isEmpty(et_address.getText().toString().trim())){
            ToastUtils.showToast("请填写公司厂房地址");
            return;
        }

    }

    private void doEdit() {
        StringRequest jor = new StringRequest(Request.Method.POST, Constant.URL_EDIT_PROTECT_ADDRESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---edit address--->" + s);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap map = new HashMap();
                map.put("true_name", "true_name" + MyApplication.getmInstance().getUsername());
                map.put("area_info",MyTool.getText(tv_area));
                map.put("address",MyTool.getText(et_address));
                map.put("area_id",areaId);
                map.put("city_id",cityId);
                map.put("gsmc",MyTool.getText(et_company));
                map.put("gsfzr",MyTool.getText(et_farenName));
                map.put("gsfzr_tel",MyTool.getText(et_farenPhone));
                map.put("jsfzr",MyTool.getText(et_techName));
                map.put("jsfzr_tel",MyTool.getText(et_techPhone));
                map.put("address_id",address.getAddress_id());
                map.put("key", MyApplication.getmInstance().getKey());
                RLog.s("----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(jor);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()){
            case R.id.address_sheng:
                adapterCity.clear();
                if(dataSheng.size() > 0){
                    City city = dataSheng.get(position);
                    shengChoose = city.getName();
                    getCity(city.getId(),"2");
                }
                break;
            case R.id.address_city:

                adapterArea.clear();
                if(dataCity.size() > 0){
                    City city = dataCity.get(position);
                    cityId = city.getId();
                    cityChoose = city.getName();
                    getCity(city.getId(),"3");
                }
                break;
            case R.id.address_area:

                if(dataArea.size() > 0){
                    City city = dataArea.get(position);
                    areaChoose = city.getName();
                    areaId = city.getId();
                }
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * 增加地址
     */
    private void doAdd() {
        StringRequest jor = new StringRequest(Request.Method.POST, Constant.URL_ADD_PROTECT_ADDRESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---address--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                if(datas.has("error")){
                                    String error = datas.getString("error");
                                    ToastUtils.showToast(error);
                                }else if(datas.has("address_id")){
                                    finish();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap map = new HashMap();
                map.put("true_name", "true_name" + MyApplication.getmInstance().getUsername());
                map.put("area_info",MyTool.getText(tv_area));
                map.put("address",MyTool.getText(et_address));
                map.put("area_id",areaId);
                map.put("city_id",cityId);
                map.put("gsmc",MyTool.getText(et_company));
                map.put("gsfzr",MyTool.getText(et_farenName));
                map.put("gsfzr_tel",MyTool.getText(et_farenPhone));
                map.put("jsfzr",MyTool.getText(et_techName));
                map.put("jsfzr_tel",MyTool.getText(et_techPhone));
                map.put("key", MyApplication.getmInstance().getKey());
                System.out.println("----params---->" + map.toString());
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(jor);
    }
}
